﻿using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using KnowledgeNotebook.DAL;
using KnowledgeNotebook.Properties;
using TXTextControl;

namespace KnowledgeNotebook.Forms
{
    public partial class frmAddOrUpdate : Form
    {
        public static frmAddOrUpdate AddForm;
        private int _imageIndex;
        private string _savepath;
        private bool _isalreadysaved;

        private Color _color;
        private bool _isfirstloadcolordialog;


        public frmAddOrUpdate()
        {
            InitializeComponent();
            txtDetail.RulerBar = rulerBar2;
            txtDetail.ButtonBar = buttonBar1;
            txtDetail.StatusBar = statusBar1;
            txtDetail.VerticalRulerBar = rulerBar1;


            AddForm = this;
            Id = 0;
            Title = String.Empty;
            Detail = String.Empty;
            _savepath = String.Empty;
            _isalreadysaved = false;

            _color = Color.Black;
            _isfirstloadcolordialog = true;
        }
        private int _id;
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
        private string _title;
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }

        private string _detail;
        public string Detail
        {
            get { return _detail; }
            set { _detail = value; }
        }

        private int _columncount;
        public int ColumnCount
        {
            set { _columncount = value; }
        }

        private int _rowcount;
        public int RowCount
        {
            set { _rowcount = value; }
        }

        //private BackgroundWorker _backgroudwordker;
        // public DataTable Data { get; set; }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }



        private void btnOption_Click(object sender, EventArgs e)
        {
            timer.Enabled = true;
            imgProgress.Enabled = true;
            imgProgress.Visible = true;
            lblInfo.Image = null;
            lblInfo.Visible = true;
            lblInfo.Text = Resources.OptionProcessing;
            DatabaseOption dbo = new DatabaseOption();
            try
            {
                if (txtTitle.Text != String.Empty)
                {
                    string title = txtTitle.Text;
                    string temp;
                    txtDetail.Save(out temp, StringStreamType.RichTextFormat);
                    string detail = temp;//
                    if (Title==String.Empty)
                    {
                        Title = txtTitle.Text;ThreadPool.QueueUserWorkItem(delegate
                                                  {
                                                      int code = dbo.InsertData(title, detail);
                                                      try
                                                      {
                                                          BeginInvoke((MethodInvoker)delegate
                                                                                          {
                                                                                              lblInfo.Visible = true;
                                                                                              if (code == 1)
                                                                                              {
                                                                                                  lblInfo.Image = Resources.OK;
                                                                                                  lblInfo.Text = Resources.OptionSuccess;
                                                                                              }
                                                                                              else
                                                                                              {
                                                                                                  lblInfo.Image = Resources.Cancel;
                                                                                                  lblInfo.Text = Resources.OptionFailed;
                                                                                              }
                                                                                              imgProgress.Enabled = false;
                                                                                              imgProgress.Visible = false;
                                                                                              timer.Enabled = false;
                                                                                              _imageIndex = 0;
                                                                                          });
                                                      }
                                                      catch (Exception ex)
                                                      {
                                                          Tip.Tip.ShowMsg(Resources.ErrorCaption, ex.Message);
                                                      }
                                                  }
                                                  );
                    }
                    else
                    {
                        ThreadPool.QueueUserWorkItem(delegate
                                                  {
                                                      int code = dbo.UpdateData(Id,title, detail);
                                                      try
                                                      {
                                                          BeginInvoke((MethodInvoker)delegate
                                                                                          {
                                                                                              lblInfo.Visible = true;
                                                                                              if (code == 1)
                                                                                              {
                                                                                                  lblInfo.Image = Resources.OK;
                                                                                                  lblInfo.Text = Resources.OptionSuccess;
                                                                                              }
                                                                                              else
                                                                                              {
                                                                                                  lblInfo.Image = Resources.Cancel;
                                                                                                  lblInfo.Text = Resources.OptionFailed;
                                                                                              }
                                                                                              imgProgress.Enabled = false;
                                                                                              imgProgress.Visible = false;
                                                                                              timer.Enabled = false;
                                                                                              _imageIndex = 0;
                                                                                          });
                                                      }
                                                      catch (Exception ex)
                                                      {
                                                          Tip.Tip.ShowMsg(Resources.ErrorCaption, ex.Message);
                                                      }
                                                  }
                                                  );
                    }
                    }
                else
                {
                    Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, Resources.TitleNotNull);
                    lblInfo.Image = Resources.Cancel;
                    lblInfo.Text = Resources.OptionFailed;
                    imgProgress.Enabled = false;
                    imgProgress.Visible = false;
                    timer.Enabled = false;
                    _imageIndex = 0;}
            }catch (Exception ex)
            {
                Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, ex.Message);
            }
        }
        private void frmAddOrUpdate_Load(object sender, EventArgs e)
        {           
            if (Title != String.Empty)
            {
                txtTitle.Text = Title;
               // string temp;
                txtDetail.Load(Detail,StringStreamType.RichTextFormat);
                //txtDetail.Text = Detail;//
            }
        }
        private void Export(FileFormat format)
        {
            saveFileDialog.Title = Resources.ExportFile;
            saveFileDialog.FileName = txtTitle.Text;
            if (DialogResult.OK == saveFileDialog.ShowDialog() && saveFileDialog.FileName != String.Empty)
            {
                StreamType streamType = StreamType.PlainText;
                switch (format)
                {
                    case FileFormat.Word2003:
                        saveFileDialog.Filter = Resources.DocFormat;
                        streamType = StreamType.MSWord;
                        break;
                    case FileFormat.Word2007:
                        saveFileDialog.Filter = Resources.DocxFormat;
                        streamType = StreamType.WordprocessingML;
                        break;
                    case FileFormat.Pdf:
                        saveFileDialog.Filter = Resources.PdfFormat;
                        streamType = StreamType.AdobePDF;
                        break;
                    case FileFormat.Txt:
                        saveFileDialog.Filter = Resources.TxtFormat;
                        streamType = StreamType.PlainText;
                        break;
                }
                try
                {
                    txtDetail.Save(saveFileDialog.FileName, streamType);
                    lblInfo.Visible = true;lblInfo.Image = Resources.OK;
                    lblInfo.Text = Resources.FileAlreadyExport;
                }
                catch (Exception)
                {
                    lblInfo.Visible = true;
                    lblInfo.Image = Resources.Cancel;
                    lblInfo.Text = Resources.ExportFailed;
                }
                //timer.Enabled = true;
                //imgProgress.Enabled = true;
                //imgProgress.Visible = true;
                //lblInfo.Visible = true;
                //lblInfo.Image = null;
                //lblInfo.Text = Resources.ExportFileProcessing;
                //int code;
                //string tmp;
                //txtDetail.Save(out tmp, StringStreamType.RichTextFormat);
                //byte[] buff = Encoding.Default.GetBytes(tmp);//
                //ThreadPool.QueueUserWorkItem(delegate
                //                                 {
                //                                     using (MemoryStream ms = new MemoryStream(buff))
                //                                     {
                //                                         Document doc = new Document(ms);
                //                                         try
                //                                         {//new DocumentBuilder(doc);
                //                                             doc.Save(saveFileDialog.FileName);
                //                                            // doc.
                //                                             //doc.Remove();
                //                                             code = 1;
                //                                         }
                //                                         catch (Exception)
                //                                         {
                //                                             //lblInfo.Image = Resources.Cancel;
                //                                             //lblInfo.Text = ex.Message;//Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, ex.Message);
                //                                             code = 0;
                //                                         }
                //                                         finally
                //                                         {
                //                                             ms.Close();
                //                                         }
                //                                         ms.Dispose();
                //                                     }
                //                                     try
                //                                     {
                //                                         BeginInvoke((MethodInvoker)delegate
                //                                                                         {
                //                                                                             lblInfo.Visible = true;
                //                                                                             //lblInfo.Text = Resources.ExportSuccess;
                //                                                                             if (code == 1)
                //                                                                             {
                //                                                                                 lblInfo.Image = Resources.OK;
                //                                                                                 lblInfo.Text = Resources.ExportSuccess;
                //                                                                             }
                //                                                                             else
                //                                                                             {
                //                                                                                 lblInfo.Image = Resources.Cancel;
                //                                                                                 lblInfo.Text = Resources.ExportFailed;
                //                                                                             }
                //                                                                             imgProgress.Enabled = false;
                //                                                                             imgProgress.Visible = false;
                //                                                                             timer.Enabled = false;
                //                                                                             _imageIndex = 0;
                //                                                                         });
                //                                     }
                //                                     catch (Exception exception)
                //                                     {
                //                                         Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, exception.Message);
                //                                     }
                //                                 });
            }
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            Export(FileFormat.Word2003);
        }
        private void menuExportWord2003_Click(object sender, EventArgs e)
        {
            Export(FileFormat.Word2003);
        }
        private void menuExportWord2007_Click(object sender, EventArgs e)
        {
            Export(FileFormat.Word2007);
        }
        private void menuExportPdf_Click(object sender, EventArgs e)
        {
            Export(FileFormat.Pdf);
        }
        private void menuExportTxt_Click(object sender, EventArgs e)
        {
            Export(FileFormat.Txt);
        }
        private void btnImport_Click(object sender, EventArgs e)
        {
            _isalreadysaved = false;
            _savepath = String.Empty;
            openFileDialog.Title = Resources.ImportFromFile;
            openFileDialog.Filter =
                Resources.SupportFormat;
            openFileDialog.FileName = String.Empty;
            if (DialogResult.OK == openFileDialog.ShowDialog() && openFileDialog.FileName != String.Empty)
            {
                try
                {
                    FileInfo fi = new FileInfo(openFileDialog.FileName);
                    string extention = fi.Extension.ToUpper();
                    switch (extention)
                    {
                        case ".RTF":
                            txtDetail.Load(openFileDialog.FileName, StreamType.RichTextFormat);
                            break;
                        case ".DOC":txtDetail.Load(openFileDialog.FileName, StreamType.MSWord);
                            break;
                        case ".DOCX":
                            //string tmp;
                            FileStream fs=new FileStream(openFileDialog.FileName,FileMode.Open);
                            txtDetail.Load(fs,StreamType.WordprocessingML);
                            fs.Close();
                            break;
                        case ".PDF":txtDetail.Load(openFileDialog.FileName, StreamType.AdobePDF);
                            break;
                        //case ".PDFA":
                        //    txtDetail.Load(openFileDialog.FileName, StreamType.AdobePDFA);
                        //    break;
                        default:
                            txtDetail.Load(openFileDialog.FileName, StreamType.PlainText);
                            break;
                    }
                    //if (extention == ".RTF" || extention == ".TXT" || extention == ".HTML" || extention == ".HTM" ||
                    //    extention == ".XML" || extention == ".DOCX" || extention == ".MHT" || extention == ".ODT")
                    //{
                    //    txtDetail.Load(StreamType.All | StreamType.RichTextFormat | StreamType.PlainText | StreamType.HTMLFormat | StreamType.XMLFormat | StreamType.MSWord | StreamType.AdobePDF | StreamType.AdobePDFA);
                    //}
                    //else
                    //{
                    //}
                }
                catch (Exception ex)
                {
                    Tip.Tip.ShowErrorMsg(Resources.ErrorCaption, ex.Message);
                }
            }
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            _imageIndex += 1;
            imgProgress.Value = _imageIndex;
            if (_imageIndex >= 100)
            {
                _imageIndex = 0;
            }
        }
        #region Nested type: FileFormat
        private enum FileFormat
        {
            Word2003,
            Word2007,
            Pdf,
            Txt
        }
        #endregion
        private void SaveFile()
        {
            if (_isalreadysaved == false)
            {
                saveFileDialog.Title = "保存文件";
                saveFileDialog.FileName = "未命名文件";saveFileDialog.Filter = string.Format("{0}|{1}", Resources.DocFormat, Resources.DocxFormat);
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _isalreadysaved = true;
                     FileInfo fi = new FileInfo(saveFileDialog.FileName);
                    string extention = fi.Extension.ToUpper();
                    if (extention == ".DOC")
                    {
                        txtDetail.Save(saveFileDialog.FileName, StreamType.MSWord);
                        _savepath = saveFileDialog.FileName;
                        lblInfo.Visible = true;
                        lblInfo.Image = Resources.OK;
                        lblInfo.Text = Resources.FileAlreadySaved;
                    }
                    else
                    {
                       txtDetail.Save(saveFileDialog.FileName, StreamType.WordprocessingML);
                        _savepath = saveFileDialog.FileName;
                        lblInfo.Visible = true;
                        lblInfo.Image = Resources.OK;
                        lblInfo.Text = Resources.FileAlreadySaved;
                    }
                }
            }
            else
            {
                FileInfo fi=new FileInfo(_savepath);
                string extention = fi.Extension.ToUpper();
                if (extention==".DOC")
                {
                    txtDetail.Save(_savepath, StreamType.MSWord);
                    lblInfo.Image = Resources.OK;
                    lblInfo.Text = Resources.FileAlreadySaved;
                }
                else
                {
                    txtDetail.Save(_savepath, StreamType.WordprocessingML);
                    lblInfo.Image = Resources.OK;
                    lblInfo.Text= Resources.FileAlreadySaved;
                }
            }
        }
        private void txtDetail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.A:
                        txtDetail.SelectAll();
                        break;
                    case Keys.S:
                        SaveFile();break;
                }
            }
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes==MessageBox.Show(Resources.AddNewContent,Resources.Tip,MessageBoxButtons.YesNo,MessageBoxIcon.Question))
            {
                txtDetail.Clear();
                txtDetail.ResetContents();
                _isalreadysaved = false;
                _savepath = String.Empty;
                txtTitle.Clear();
                Title = String.Empty;
                lblInfo.Image = null;
                lblInfo.Text = String.Empty;
                lblInfo.Visible = false;
            }
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show(Resources.ClearContent, Resources.Tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                txtDetail.Clear();
                txtDetail.ResetContents();
                _isalreadysaved = false;
                _savepath = String.Empty;
                lblInfo.Image = null;
                lblInfo.Text = String.Empty;
                lblInfo.Visible = false;
            }
        }

        private void btnSetColor_Click(object sender, EventArgs e)
        {
            colorDialog.ShowDialog();

            if (_isfirstloadcolordialog)
            {
                
                _color = colorDialog.Color;
            }
            else
            {
                colorDialog.Color = _color;
            }

            txtDetail.Selection.ForeColor = colorDialog.Color;

            
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        { 
            PrintDocument pDoc=new PrintDocument();
            pDoc.DocumentName = txtTitle.Text;
            txtDetail.PrintPreview(pDoc);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pDoc = new PrintDocument();
            pDoc.DocumentName = txtTitle.Text;
            txtDetail.Print(pDoc);
        }

        private void btnInsertTable_Click(object sender, EventArgs e)
        {
            using (frmInsertTable insertTable=new frmInsertTable())
            {
                if (DialogResult.OK==insertTable.ShowDialog())
                {
                    txtDetail.Tables.Add(_rowcount, _columncount);}
            }
        }
    }
}